package com.qf.commons.web.valid;

import com.qf.commons.web.utils.ApplicationUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * description: 自定义校验处理器
 * author: Ken
 * 公众号：Java架构栈
 */
public class CustemValidHandler implements ConstraintValidator<CustemValid, Object> {

    private CustemValid custemValid;

    @Override
    public void initialize(CustemValid constraintAnnotation) {
        this.custemValid = constraintAnnotation;
    }

    /**
     * 核心的校验方法
     * @param value
     * @param context
     * @return
     */
    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        //执行校验逻辑，返回true表示校验通过，返回false表示校验未通过
        if (value != null) {
            //获取开发者自定义的处理器类型
            Class<? extends KenValid> handlerClass = custemValid.handler();

            //通过开发者的类型从容器中获取Bean对象
            KenValid kenValid = ApplicationUtils.getBean(handlerClass);
            if (kenValid == null) return true;
            return kenValid.isValid(custemValid, value);
        }
        return true;
    }
}
